#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#include <errno.h>

/*
 * get process's time slice
 * used systemcall: int sched_rr_get_interval(pid_t pid, struct timespec * tp)
 * sched_rr_get_interval() writes into the timespec structure pointed to by tp the round-robin time quantum for the process identified by pid.
 * The timespec structure has the following form:
 *
 * struct timespec {
 *      time_t tv_sec;    // seconds 
 *      long   tv_nsec;   //nanoseconds
 *      };
 */

int main(int argc, char* argv[])
{
	if(argc != 2)
	{
		printf("Usage: %s <pid>\n", argv[0]);
		exit(0);
	}
	int pid = atoi(argv[1]);
	struct timespec tm;
	int ret = sched_rr_get_interval(pid, &tm);
	if(ret != 0)
	{
		switch(errno)
		{
			case EFAULT:
				printf("Problem with copying information to userspace.\n");
				break;
			case EINVAL:
			       printf("Invalid pid.\n");
			       break;
			case ENOSYS:
			       printf("The system call is not yet implemented (only on rather old kernels).\n");
			       break;
			case ESRCH:
			       printf("The process whose ID is %d could not be found.\n", pid);
			       break;
		}
		exit(1);
	}

	printf("pid: %d  timeslice: %d s  %ld nanos \n", pid, tm.tv_sec, tm.tv_nsec);

	return 0;
}
